<?php
//-------------------------------------------------------------------------------------------------------
    require_once($config['app_dir'] . '/includes/object.class.php');
    require_once($config['app_dir'] . '/includes/db.class.php');
    //---------------------------------------------------------------------------------------------------
    class objStockMailerModel extends objObject implements iErrorHandler {
            public $mailer_session_id = false;

            protected $_group_id = -1;
            protected $_error_str = array('no error');
            protected $_db  = false;
            protected $_sql_querys = array();

            public $_forecasts = false;

        public function __construct($aGroup=-1) {
            $this->_group_id = intval($aGroup);

            $this->_db = objDataBase::GetInstance();
            $this->_sqls();
        }//constructor

        public function ClassName() {
            return  __CLASS__;
        }//ClassName

        protected function buildWhere($type=1, $trades=false, $systems=false, $trades_systems=false) {
            $where='';

            if( false!==$type ) $where .= " and MessageType=$type ";

            if( false!==$trades ) {
                if( is_array($trades) ) {
                    $trade = implode(',',$trades);
                    $where .= " and t.TradeID in ($trade) ";
                }
                else $where .= " and t.TradeID=$trades ";
            }//trades

            if( false!==$systems ) {
                if( is_array($systems) ) {
                    $system = implode(',', $systems);
                    $where .= " and s.SystemID in ($system) ";
                }
                else $where .= " and s.SystemID=$systems ";
            }//systems

            if( false!=$trades_systems && is_array($trades_systems) ){
                $tmp = '';
                foreach( $trades_systems as $item ) {
                    $tmp .= '( s.SystemID = '.$item['SystemID'].' AND t.TradeID = ' . $item['TradeID'].') OR ';
                }//foreach
                if( $tmp ) {
                    $tmp = substr($tmp, 0, -4);
                    $where .= " AND ($tmp)";
                }
            }//trades_systems
            $this->_sqls();
            if( $this->mailer_session_id ) $where .= $this->_sql_querys['session_clause'];

            return $where;
        } //buildWhere
        //-------------------------------------------------------------------------------------------------------------
        // Depreceted
        public function getEmails($type=1, $trades=false, $messagetype=1, $systems=false, $trades_systems=false) {
            $query = $this->_sql_querys['emails'] . $this->buildWhere($type, $trades, $systems, $trades_systems);
            $query .= $this->_sql_querys['sort'];
            $data_emails = $this->_db->handler->getAll($query);
            $emails = array();
            foreach($data_emails as $item) {
                if( $item['Login'] ) $emails[$item['Login']] = strval($item['Name']);
            }//foreach
            return $emails;
        } //getEmails

        public function GetSMSEmails($type=1, $trades=false, $systems=false, $trades_systems=false) {
            $query = $this->_sql_querys['smsemails'] . $this->buildWhere($type, $trades, $systems, $trades_systems);

            $query .= $this->_sql_querys['sort'];
            $data_emails = $this->_db->handler->getAll($query);

            $emails = array();
            foreach($data_emails as $item) {
                if( $item['SMSAddress'] ) $emails[$item['SMSAddress']] = strval($item['Name']);
            }//foreach
            return $emails;
        } //GetSMSEmails
        // /Depreceted
        //-------------------------------------------------------------------------------------------------------------
        public function getEmailsArr($type=1, $trades=false, $systems=false, $trades_systems=false) {
            $query = $this->_sql_querys['emails'] . $this->buildWhere($type, $trades, $systems, $trades_systems);

            $query .= $this->_sql_querys['sort'];
            $data_emails = $this->_db->handler->getAll($query);

            $result = array(); $i = 0;
            foreach($data_emails as $item) {
                if( $item['Login'] ) {
                    $result[$i]['id'] = strval($item['UserID']);
                    $result[$i]['name'] = strval($item['Name']);
                    $result[$i]['email'] = strval($item['Login']);
                    $result[$i]['language'] = strval($item['Language']);
                    $i++;
                }
            }//foreach
            return $result;
        } //getEmails

        public function GetSMSEmailsArr($type=1, $trades=false, $systems=false, $trades_systems=false) {
            $query = $this->_sql_querys['smsemails'] . $this->buildWhere(false, $trades, $systems, $trades_systems);

            $query .= $this->_sql_querys['sort'];
            $data_emails = $this->_db->handler->getAll($query);

            $result = array(); $i = 0;
            foreach($data_emails as $item) {
                if( $item['SMSAddress'] ) {
                    $result[$i]['id'] = strval($item['UserID']);
                    $result[$i]['name'] = strval($item['Name']);
                    $result[$i]['email'] = strval($item['SMSAddress']);
                    $result[$i]['language'] = strval($item['Language']);
                    $i++;
                }
            }//foreach
            return $result;
        } //GetSMSEmails

        public function GetSMSDirectArr($type=1, $trades=false, $systems=false, $trades_systems=false) {
            $query = $this->_sql_querys['smsdirect'] . $this->buildWhere(false, $trades, $systems, $trades_systems);

            $data_emails = $this->_db->handler->getAll($query);

            $result = array(); $i = 0;
            foreach($data_emails as $item) {
                if( $item['PhoneCode'] ) {
                    $result[$i]['id'] = strval($item['UserID']);
                    $result[$i]['name'] = strval($item['Name']);
                    $result[$i]['email'] = strval($item['PhoneCode']).strval($item['PhoneNumber']);
                    $result[$i]['language'] = strval($item['Language']);
                    $i++;
                }
            }//foreach
            return $result;
        } //GetSMSDirectArr

        public function getPeriods($trades=false, $systems=false, $trades_systems=false) {

            $query = $this->_sql_querys['maxclose'] . $this->buildWhere(false, $trades, $systems, $trades_systems);
            $data = $this->_db->handler->getAll($query);
            $periods = array();  $i=0;
            foreach($data as $item) {
                $periods[$i]['trade'] = intval($item['TradeID']);
                $periods[$i]['system'] = intval($item['SystemID']);
                $periods[$i]['pair'] = strval($item['Pair']);
                $periods[$i]['start'] = strval($item['TimeStart']);
                $periods[$i]['finish'] = strval($item['TimeFinish']);
                $periods[$i]['beginprice'] = floatval($item['BeginPrice']);
                $periods[$i]['endprice'] = floatval($item['EndPrice']);
                $periods[$i]['begintime'] = floatval($item['BeginTime']);
                $periods[$i]['endtime'] = floatval($item['EndTime']);
                ++$i;
            } //foreach
            return $periods;
        } //GetPeriods

        public function getLanguages() {
            return $this->_db->handler->getAll($this->_sql_querys['languages']);
        } //getLanguages

        protected function _sqls() {
            $this->_sql_querys['languages'] =
                'SELECT * from fa_language';
            //-----------------------------------------------------------------------------------------------------
            $this->_sql_querys['sort'] = " ORDER BY  COALESCE(u.subscr_active,0) desc ";

            $this->_sql_querys['session_clause'] =
                " AND not exists( ".
	                 " SELECT m.UserID ".
	                 " FROM fa_mailer_mails m ".
	                 " WHERE m.MessageType=u.MessageType ".
		                  " AND m.UserID=u.UserID ".
		                  " AND m.SessionID=". $this->mailer_session_id.")";


            $this->_sql_querys['emails'] =
                " SELECT DISTINCT ".
                  " u.UserID, ".
                  " u.Login, ".
                  " u.Name, ".
                  " u.MessageType, ".
                  " u.Active, ".
				  " u.Language, ".
                  " t.TradeID, ".
                  " t.Pair, ".

                  " u.SMSAddress, ".
                  "	ut.SystemID ".
                 " FROM ".
                     " fa_users_trades ut ".
                     " LEFT OUTER JOIN( ".
                        " SELECT * ".
                        " FROM ".
                         " fa_users tu ".
                         " LEFT OUTER JOIN fa_subscriptions ts ON (ts.user_id = tu.UserID) ".
                        " WHERE ts.subscr_active=1 ".
                              "  OR ".
                             " (UNIX_TIMESTAMP()-tu.ActivationTime)<1209600 ".
                             "  OR ".
                             " tu.GroupID=3 ".
                      " ) u ON (ut.UserID = u.UserID) ".
                     " LEFT OUTER JOIN fa_trades t ON (ut.TradeID = t.TradeID) ".
                     " LEFT OUTER JOIN fa_systems s ON (ut.SystemID = s.SystemID) ".
                 " WHERE u.Active=1 AND s.Active=1 ";

            if( 1==$this->group_id )  $this->_sql_querys['emails'] .= " AND ( u.GroupID=1)";
            //-----------------------------------------------------------------------------------------------------
            $this->_sql_querys['smsemails'] =
                " SELECT DISTINCT ".
                  " u.UserID, ".
                  " u.Login, ".
                  " u.Name, ".
                  " u.MessageType, ".
                  " u.Active, ".
				  " u.Language, ".
                  " t.TradeID, ".
                  " t.Pair, ".
                  " u.SMSAddress, ".
                  "	ut.SystemID ".
                 " FROM ".
                     " fa_users_trades ut ".
                     " LEFT OUTER JOIN( ".
                        " SELECT * ".
                        " FROM ".
                         " fa_users tu ".
                         " LEFT OUTER JOIN fa_subscriptions ts ON (ts.user_id = tu.UserID) ".
                        " WHERE tu.SMSAddress is not null AND ts.subscr_active=1 ".
                              "  OR ".
                             " (UNIX_TIMESTAMP()-tu.ActivationTime) <1209600 ".
                      " ) u ON (ut.UserID = u.UserID) ".
                     " LEFT OUTER JOIN fa_trades t ON (ut.TradeID = t.TradeID) ".
                     " LEFT OUTER JOIN fa_systems s ON (ut.SystemID = s.SystemID) ".
                 " WHERE u.Active=1 AND s.Active=1 ";
            if( 1==$this->group_id )  $this->_sql_querys['smsemails'] .= " AND ( u.GroupID=1)";
            //-----------------------------------------------------------------------------------------------------
            $this->_sql_querys['smsdirect'] =
                " SELECT DISTINCT ".
                  " u.UserID, ".
                  " u.Login, ".
                  " u.Name, ".
                  " u.MessageType, ".
                  " u.Active, ".
				  " u.Language, ".
                  " t.TradeID, ".
                  " t.Pair, ".
                  " u.PhoneCode, u.PhoneNumber, ".
                  "	ut.SystemID ".
                 " FROM ".
                     " fa_users_trades ut ".
                     " LEFT OUTER JOIN( ".
                        " SELECT * ".
                        " FROM ".
                         " fa_users tu ".
                         " LEFT OUTER JOIN fa_subscriptions ts ON (ts.user_id = tu.UserID) ".
                        " WHERE tu.PhoneCode is not null AND tu.PhoneNumber is not null AND ts.subscr_active=1 ".
                              "  OR ".
                             " (UNIX_TIMESTAMP()-tu.ActivationTime) <1209600 ".
                      " ) u ON (ut.UserID = u.UserID) ".
                     " LEFT OUTER JOIN fa_trades t ON (ut.TradeID = t.TradeID) ".
                     " LEFT OUTER JOIN fa_systems s ON (ut.SystemID = s.SystemID) ".
                 " WHERE u.Active=1 AND s.Active=1 ";
            if( 1==$this->group_id )  $this->_sql_querys['smsdirect'] .= " AND ( u.GroupID=1)";
            //-----------------------------------------------------------------------------------------------------
            $this->_sql_querys['actual'] =
                " SELECT f.TradeID, ".
                       " t.Pair, ".
                       " f.EndPrice, ".
                       " s.SystemID, " .
                       " date_format(FROM_UNIXTIME(f.EndTime)- interval 11 day, '%Y-%m-%d %H:%i:%s' ) as TimeStart, ".
                       " FROM_UNIXTIME(f.EndTime, '%Y-%m-%d %H:%i:%s') as TimeFinish ".
                " FROM vfa_forecast f ".
                      " LEFT OUTER JOIN fa_trades t ON (f.TradeID = t.TradeID) ".
                      "	LEFT OUTER JOIN fa_systems s ON (f.SystemID = s.SystemID) ".
                " WHERE f.EndTime>=unix_timestamp() AND s.Active=1";
            //-----------------------------------------------------------------------------------------------------
            $this->_sql_querys['maxclose'] =
                " SELECT f.TradeID, ".
                       " t.Pair, ".
                       " f.EndPrice, ".
                       " f.BeginPrice, ".
                       " f.EndTime, ".
                       " f.BeginTime, ".
                       " s.SystemID, " .
                       " date_format(FROM_UNIXTIME(f.EndTime)- interval 9 day, '%Y-%m-%d %H:%i:%s')  as TimeStart, ".
                       " FROM_UNIXTIME(f.EndTime, '%Y-%m-%d %H:%i:%s') as TimeFinish ".
                " FROM vfa_forecast f ".
                      " LEFT OUTER JOIN fa_trades t ON (f.TradeID = t.TradeID) ".
                      " LEFT OUTER JOIN fa_systems s ON (f.SystemID = s.SystemID) ".
                " WHERE f.CloseTime is null  AND s.Active=1 ".
                                " AND f.BeginTime + 2*f.EndTime - 3*COALESCE(f.CloseTime, 0)= ".//
                                " (SELECT MAX(tmp_f.BeginTime + 2*tmp_f.EndTime - 3*COALESCE(tmp_f.CloseTime,0)) ".
                                 " FROM vfa_forecast tmp_f ".
                                 " WHERE tmp_f.TradeID=f.TradeID AND tmp_f.SystemID=f.SystemID)";//.


        } //_SQLs

    } //class objStockMailerModel
//-------------------------------------------------------------------------------------------------------
?>
